import inspect
from typing import Optional, Awaitable, Callable, Any
from fastapi import Request, Response, FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response as StarletteResponse
from starlette.types import ASGIApp
from src.services import RateLimiter
from src.utils.logging import get_logger

# 使用延迟导入避免循环依赖
def get_encryption_service():
    try:
        from src.services.encryption_service import encryption_service
        return encryption_service
    except ImportError:
        return None

logger = get_logger(__name__)

class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    """安全头中间件，增强对协程对象和非标准响应的处理能力"""
    
    def __init__(self, app: ASGIApp, rate_limiter: Optional[RateLimiter] = None):
        super().__init__(app)
        self.rate_limiter = rate_limiter
    
    async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
        """转发请求，不进行任何处理以避免干扰框架异常处理"""
        return await call_next(request)
    
    
    def _add_security_headers(self, response: Response) -> Response:
        """为响应添加安全头"""
        # 确保response有headers属性
        if not hasattr(response, 'headers'):
            # 创建一个新的响应对象
            status_code = getattr(response, 'status_code', 500)
            
            # 创建一个基础的响应对象
            response = StarletteResponse(
                content="Internal Server Error",
                status_code=status_code
            )
        
        # 添加安全头
        try:
            response.headers["X-Content-Type-Options"] = "nosniff"
            response.headers["X-Frame-Options"] = "DENY"
            response.headers["X-XSS-Protection"] = "1; mode=block"
            response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
            # 修改CSP策略，允许加载FastAPI文档需要的外部资源
            response.headers["Content-Security-Policy"] = (
                "default-src 'self'; "
                "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
                "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
                "img-src 'self' data: https:; "
                "font-src 'self' data: https://cdn.jsdelivr.net https://fonts.gstatic.com; "
                "connect-src 'self';"
            )
            response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
        except Exception as header_error:
            logger.error(f"添加安全头失败: {header_error}")
        
        return response

def setup_security_middleware(app: FastAPI, rate_limiter: Optional[RateLimiter] = None):
    """设置安全中间件"""
    app.add_middleware(SecurityHeadersMiddleware, rate_limiter=rate_limiter)
    logger.info("安全中间件已设置")